package com.两个链表相加;

import java.util.Stack;
//缺陷：必须在范围内的数才能算出来所以有局限性
class Solution {
	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		// 将链表逆置输出并且存储起来转换成整数然后相加再转为链表
		double end1 = ReserveList(l1);
		double end2 = ReserveList(l2);
		double end = end1 + end2;
		ListNode l3 = createList(end);
		return l3;
	}
	public ListNode createList(double end) {
		
		ListNode head=new ListNode((int)(end%10));
		ListNode p=head;
		end=end/10;
		
		while(end>0) {
			int num = (int)(end%10);
			ListNode q=new ListNode(num);
			p.next=q;
			p=p.next;
			end=end/10;
		}
		return head;
	}

	public double ReserveList(ListNode l) {
		if (l == null)
			return 0;
		Stack<Integer> stack = new Stack<Integer>();
		while (l != null) {
			stack.add(l.val);
			l = l.next;
		}
		double sum = 0;
		while (!stack.isEmpty()) {
			int temp = stack.pop();
			sum = sum + temp * Math.pow(10, (double) (stack.size()));
		}

		return   sum;
	}
}